package com.cheer.ba.view.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TextView;

import com.cheer.ba.R;
import com.cheer.ba.app.App;
import com.cheer.ba.cache.preference.Session;
import com.cheer.ba.constant.ConstantTag;
import com.cheer.ba.constant.H5Address;
import com.cheer.ba.constant.IntentCode;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.constant.ReturnCode;
import com.cheer.ba.event.BaseEvent;
import com.cheer.ba.model.PushMessageModel;
import com.cheer.ba.presenter.impl.LoginPresenter;
import com.cheer.ba.utils.ClearCacheUtil;
import com.cheer.ba.utils.ClickCounter;
import com.cheer.ba.utils.LogUtils;
import com.cheer.ba.utils.NotificationsUtils;
import com.cheer.ba.utils.ShareNewsUtil;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.utils.ToastUtil;
import com.cheer.ba.view.base.CheckPermissionsAty;
import com.cheer.ba.view.dialog.DialogUtils;
import com.cheer.ba.view.fragment.CheerCircleFrg;
import com.cheer.ba.view.fragment.HomeFrg;
import com.cheer.ba.view.fragment.HomeFrg1;
import com.cheer.ba.view.fragment.MineFrg;
import com.cheer.ba.view.fragment.PlayerFrg;
import com.cheer.ba.view.tabhost.CustomFragmentTabHost;
import com.example.jpushdemo.ExampleUtil;
import com.example.jpushdemo.Logger;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.UpgradeInfo;
import com.umeng.socialize.UMShareAPI;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Set;

import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * 主界面
 */
public class MainAty extends CheckPermissionsAty implements TabHost.OnTabChangeListener {

    @BindView(R.id.id_main_content_ll)
    FrameLayout mMainContentLL;

    //底部导航栏类
    @BindView(android.R.id.tabhost)
    CustomFragmentTabHost mTabHost;

    //红点通知
    private TextView mTxtUpdate;

    public static final String[] mTabStrs = new String[]{"首页", "活动", "车友之家", "我的"};

    private ClickCounter mCounter;

    //记录当前底部下标的位置
    private int currentTab = 0;

    private Dialog dialog;

    private ShareNewsUtil mShare;

    @Override
    protected boolean isSupportBack() {
        return false;
    }

    @Override
    protected boolean isSupportSwipeback() {
        return false;
    }

    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return inflater.inflate(R.layout.aty_main, null, false);
    }

    @Override
    public void initPresenter() {
        presenter = new LoginPresenter();
    }

    @Override
    public void initView() {
        mCounter = new ClickCounter(2, 2000);
        mCounter.setListener(new ClickCounter.OnCountListener() {
            @Override
            public void onCount(int currentTime) {
                ToastUtil.showToastById(R.string.exit_2_app);
            }

            @Override
            public void onFinish() {
                finish();
            }
        });
        initBottomTab();
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mMainContentLL.getLayoutParams();
        //xml中是35多一個px
        layoutParams.setMargins(0, 0, 0, (int) (0 - getResources().getDimension(R.dimen.px36)));

        int type = getIntent().getIntExtra(IntentKey.General.KEY_TYPE, -1);
        if (type == IntentCode.Jpush.JPUSH_CLICK) {
            LogUtils.LogD("JPush", "type---------" + type);
            PushMessageModel model = (PushMessageModel) getIntent().getSerializableExtra(IntentKey.General.KEY_MODEL);
            if (null != model) {
                LogUtils.LogD("JPush", "initview---------true");
                showOtherAty(model);
            } else {
                LogUtils.LogD("JPush", "initview---------false");
            }
        }
    }

    /**
     * 展示其他activity
     */
    public void showOtherAty(PushMessageModel model) {
        //打开自定义的Activity
        Intent i = null;
        if (TextUtils.equals("1001", model.msgId)) {
            //订单支付
            if (Session.getUserIsLogin()) {
                LogUtils.LogD("JPush", "1001---已登录");
                //支付成功
                BaseEvent event = new BaseEvent();
                event.type = IntentKey.Login.KEY_NOTICE_PAY;
                EventBus.getDefault().post(event);

                i = new Intent(aty, MyOilCardAty.class);
            } else {
                LogUtils.LogD("JPush", "1001---未登录");
                i = new Intent(aty, LoginAty.class);
                i.putExtra(IntentKey.General.KEY_PAGE, IntentCode.General.BACK_ORDER);
            }
        } else if (TextUtils.equals("1002", model.msgId)) {
            LogUtils.LogD("JPush", "1002---积分变更");
            //积分变更
            BaseEvent event = new BaseEvent();
            event.type = IntentKey.Login.KEY_NOTICE_POINT;
            EventBus.getDefault().post(event);
            //积分变更
            return;
        } else if (TextUtils.equals("1003", model.msgId)) {
            //柴油卡审核通过
            if (Session.getUserIsLogin()) {
                LogUtils.LogD("JPush", "1003---柴油卡审核通过");
                i = new Intent(aty, AddOilCardAty.class);
                i.putExtra(IntentKey.General.KEY_DATA, model.data.cardNum);
            } else {
                LogUtils.LogD("JPush", "1003---未登录");
                i = new Intent(aty, LoginAty.class);
                i.putExtra(IntentKey.General.KEY_PAGE, IntentCode.General.BACK_ADD_CARD);
                i.putExtra(IntentKey.General.KEY_DATA, model.data.cardNum);
            }
        } else if (TextUtils.equals("1004", model.msgId)) {
            LogUtils.LogD("JPush", "1004---活动推送");
            //活动推送
            i = new Intent(aty, CommH5Aty.class);
            i.putExtra(IntentKey.General.KEY_URL, model.data.url);
        }
//        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(i);
    }

    @Override
    public void initData() {

        mShare = new ShareNewsUtil(aty, "为了省钱的名义！", "加油省钱？选加油啦错不了！", H5Address.SHARE_APP, "");
        EventBus.getDefault().register(this);

        /***** 检查更新 *****/
//        Beta.checkUpgrade();

        /***** 获取升级信息 *****/
        UpgradeInfo upgradeInfo = Beta.getUpgradeInfo();
        if (upgradeInfo != null) {
            BaseEvent event = new BaseEvent();
            event.type = IntentKey.Upgrade.KEY_HAD_UPDATE;
            EventBus.getDefault().post(event);
        } else {
            BaseEvent event = new BaseEvent();
            event.type = IntentKey.Upgrade.KEY_NO_UPDATE;
            EventBus.getDefault().post(event);
        }
        if (Session.getUserFirstRemindHome()) {
            checkNotification();
        }
    }

    /**
     * 检测是否有通知权限
     */
    private void checkNotification() {
        if (!NotificationsUtils.isNotificationEnabled(aty)) {
            Session.setUserFirstRemindHome(false);
            DialogUtils.showCommDialog(aty, "开启消息通知，不错过任何重要消息。", "取消", "去设置", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    DialogUtils.DialogDiss();
                    requestPermission(0);
                }
            });
            DialogUtils.DialogShow();
        }
    }


    @Override
    public void onBackPressed() {
        if (mCounter != null) {
            mCounter.countClick();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //统计时长
//        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
//        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
//        App.exit();
    }

    private void initBottomTab() {
//        if (mTabHost != null) {
//            mTabHost.removeAllViews();
//        }
        mTabHost = (CustomFragmentTabHost) findViewById(android.R.id.tabhost);

        mTabHost.setup(this, getSupportFragmentManager(), R.id.id_main_content_ll);

        mTabHost.setOnTabChangedListener(this);

        mTabHost.getTabWidget().setDividerDrawable(null);
        mTabHost.addTab(mTabHost.newTabSpec(mTabStrs[0]).setIndicator(getLayoutInflater().inflate(R.layout.layout_main_home, null)),
                HomeFrg1.class, null);
        mTabHost.addTab(mTabHost.newTabSpec(mTabStrs[1]).setIndicator(getLayoutInflater().inflate(R.layout.layout_main_player, null)),
                PlayerFrg.class, null);
        mTabHost.addTab(mTabHost.newTabSpec(mTabStrs[2]).setIndicator(getLayoutInflater().inflate(R.layout.layout_main_focus, null)),
                CheerCircleFrg.class, null);
        mTabHost.addTab(mTabHost.newTabSpec(mTabStrs[3]).setIndicator(getLayoutInflater().inflate(R.layout.layout_main_mine, null)),
                MineFrg.class, null);

        mTxtUpdate = (TextView) mTabHost.findViewById(R.id.id_update_dot_txt);
    }

    //是否点击天气
    private boolean isWeather;

    @Override
    public void onTabChanged(String tabId) {
        if (mTabStrs[0].equals(tabId)) {
            initHomeFrgTitleBar(tabId);
        } else if (mTabStrs[1].equals(tabId)) {
            initPlayerFrgTitleBar(tabId);
        } else if (mTabStrs[2].equals(tabId)) {
            initFocusFrgTitleBar(tabId);
        } else {
            initMineFrgTitleBar(tabId);
        }
    }

    //处理首页
    private void initHomeFrgTitleBar(String tabId) {
        setTitleText(tabId, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BaseEvent event = new BaseEvent();
                event.type = IntentKey.General.KEY_CLICK;
                EventBus.getDefault().post(event);
            }
        });
        clearRightIcon();
        showLeftIcon(R.drawable.ic_home_weather, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //进入天气
                isWeather = true;
                checkWeatherPermiss();
            }
        });
//        setTitleIcon(R.drawable.ic_home_msg, false, new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (isLogin(true)) {
//                    showActivity(aty, MessageAty.class);
//                }
//            }
//        });
    }

    //处理活动页
    private void initPlayerFrgTitleBar(String tabId) {
        setTitleText(tabId);
        clearRightIcon();
        setTitleIcon(R.drawable.ic_sharer, false, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mShare.showShare();
            }
        });
    }

    //处理发现页
    private void initFocusFrgTitleBar(String tabId) {
        setTitleText(tabId);
        clearRightIcon();
    }

    //处理我的页
    private void initMineFrgTitleBar(String tabId) {
        setTitleText(tabId);
        clearRightIcon();
    }

    /**
     * 检测用户定位权限
     */
    private void checkWeatherPermiss() {
        String[] perms = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
        if (!mayRequestPermission(perms)) {
            return;
        }
        getWeather();
    }

    /**
     * 获取地址
     */
    public void getWeather() {
        showActivity(aty, WeatherAty.class);
    }

    @Override
    public void requestPermissionResult(boolean allowPermission) {
        if (allowPermission) {
            if (isWeather) {
                getWeather();
                isWeather = false;
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt(IntentKey.General.KEY_POS, mTabHost.getCurrentTab());
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        currentTab = savedInstanceState.getInt(IntentKey.General.KEY_POS);
//        if (currentTab == 2) {
//            new Handler().postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    onTabChanged(mTabStrs[currentTab]);
//                }
//            }, 1500);
//        }
    }

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case IntentCode.Jpush.JPUSH_BIND_ALIAS:
                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                    break;
                case IntentCode.Jpush.JPUSH_BIND_ALIAS_NULL:
                    JPushInterface.setAliasAndTags(getApplicationContext(), "", null, mAliasCallback);
                    break;
            }
        }
    };

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Logger.i(TAG, logs);
                    if (App.REGISTER_GIFT == 1) {
                        App.REGISTER_GIFT = 0;
                        ((LoginPresenter) presenter).registerGift();
                    }
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Logger.i(TAG, logs);
                    if (ExampleUtil.isConnected(getApplicationContext())) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(IntentCode.Jpush.JPUSH_BIND_ALIAS, alias), 1000 * 60);
                    } else {
                        Logger.i(TAG, "No network");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    Logger.e(TAG, logs);
            }
//            ExampleUtil.showToast(logs, getApplicationContext());
        }
    };

    @Override
    public <T> void updateViewWithTag(T t, String tag) {
        if (null != t) {
            if (TextUtils.equals(tag, ConstantTag.REGISTER_GIFT)) {
                //注册大礼包
//                showActivity(aty, RegistGiftAty.class);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventUpdate(BaseEvent event) {
        if (TextUtils.equals(IntentKey.Upgrade.KEY_HAD_UPDATE, event.type)) {
            mTxtUpdate.setVisibility(View.VISIBLE);
        } else if (TextUtils.equals(IntentKey.Upgrade.KEY_NO_UPDATE, event.type)) {
            mTxtUpdate.setVisibility(View.GONE);
        } else if (TextUtils.equals(event.type, IntentKey.Login.KEY_START_JPUSH)) {
            //启动Jpush
            if (JPushInterface.isPushStopped(aty)) {
                JPushInterface.init(aty);
            }
//            String rid = JPushInterface.getRegistrationID(getApplicationContext());
            if (!StringUtils.isEmpty(Session.getUserId())) {
                //调用JPush API设置Alias
                mHandler.sendMessage(mHandler.obtainMessage(IntentCode.Jpush.JPUSH_BIND_ALIAS, Session.getUserId()));
            } else {
                mHandler.sendMessage(mHandler.obtainMessage(IntentCode.Jpush.JPUSH_BIND_ALIAS_NULL, ""));
            }
        } else if (TextUtils.equals(event.type, IntentKey.Login.KEY_APP_EXIT)) {
            //推出登录
            //调用JPush API设置Alias
            mHandler.sendMessage(mHandler.obtainMessage(IntentCode.Jpush.JPUSH_BIND_ALIAS_NULL, ""));
        } else if (TextUtils.equals(event.type, ConstantTag.REGISTER_GIFT)) {
            //注册大礼包
            showActivity(aty, RegistGiftAty.class);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        int type = intent.getIntExtra(IntentKey.General.KEY_TYPE, -1);
        LogUtils.LogD("JPush", "mainaty进来了----------");
        if (type == ReturnCode.USER_EXPIRE) {
            //用户过期
            if (!Session.getUserIsLogin()) {
                return;
            }

            DialogUtils.showCommDialog(aty, getString(R.string.login_expire), getString(R.string.cancel), getString(R.string.login_with_space), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    DialogUtils.DialogDiss();
                    Intent login = new Intent(aty, LoginAty.class);
                    startActivityForResult(login, IntentCode.Login.LOGIN_REQUEST_CODE);
                }
            });
            if (!isFinishing()) {
                DialogUtils.DialogShow();
            }

            ClearCacheUtil.clearCache(aty, 1, Session.getUserId());

            BaseEvent event = new BaseEvent();
            event.type = IntentKey.Login.KEY_APP_EXIT;
            EventBus.getDefault().post(event);
        } else if (type == IntentCode.Jpush.JPUSH_CLICK) {
            //点击推送
            LogUtils.LogD("JPush", "点击推送--------------mainaty");
            Bundle bundle = getIntent().getExtras();
            if (null != bundle) {
                PushMessageModel model = (PushMessageModel) bundle.getSerializable(IntentKey.General.KEY_MODEL);
                if (null != model) {
                    LogUtils.LogD("JPush", model.toString());
                    showOtherAty(model);
                } else {
                    LogUtils.LogD("JPush", "onnewintent---false");
                }
            } else {
                LogUtils.LogD("JPush", "onnewintent---false---bundle");
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
